package com.sixiaolong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sixiaolong.dao.DishDao;
import com.sixiaolong.domain.Dish;
import com.sixiaolong.domain.DishDto;
import com.sixiaolong.domain.DishFlavor;
import com.sixiaolong.service.DishFlavorService;
import com.sixiaolong.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishDao, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;
    /**
     * 新增菜品，同时保存对应的口味数据
     * @param dishDto
     */
    @Override
    @Transactional   //事务注解  在涉及到多张表同步添加操作时为保证同时成功和同时失败
    public void saveWithFlavor(DishDto dishDto) {
//        this==dishService  保存菜品的基本信息到菜品表dish
        this.save(dishDto);
        Long dishId = dishDto.getId(); //菜品id
//        获取Flavors口味数据  并遍历每个加上Id 可以进行匹配
        List<DishFlavor> flavors = dishDto.getFlavors();
//        遍历flavors集合  给每个对象加一个dishId
        flavors.forEach(flavor -> {
            flavor.setDishId(dishId);
        });
//         插入flavors
        dishFlavorService.saveBatch(flavors);
    }

//  根据id查询菜品
    @Override
    public DishDto getByIdWithFlavor(Long id) {
//        查询菜品
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
//        把普通的属性都拷贝到dishdto中
        BeanUtils.copyProperties(dish,dishDto);
//        查询口味
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> dishFlavors = dishFlavorService.list(lqw);
//        DishFlavor dishFlavor = dishFlavorService.getById(dish.getId());
        dishDto.setFlavors(dishFlavors);
        return dishDto;
    }

    /**
     * 修改菜品信息
     * @param dishDto
     */
    @Override
//    涉及到两张表以上的增删改都要开启事务  同时成功同时失败
    @Transactional
    public void updateFlavor(DishDto dishDto) {
//        更新dish基本信息
        this.updateById(dishDto);
//        清理当前菜品对应的口味数据---dish_flavors的delete操作  删除所有原先已绑定的菜品口味   之后添加新的口味
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(lqw);
//        添加当前提交过来的口味数据---dish_flavors的insert操作
//        dishFlavorService.updateBatchById(flavors);
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(e -> {
//           把菜品id和口味id绑定起来
            e.setDishId(dishDto.getId());
        });
        dishFlavorService.saveBatch(flavors);
    }
}
